package org.answer.controller;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.answer.constant.MessageConstant;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.entity.Result;
import org.answer.pojo.Permission;
import org.answer.service.PermissionService;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.apache.dubbo.config.annotation.Reference;

import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 权限管理
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Reference
    private PermissionService permissionService;
    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();
    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = permissionService.pageQuery(queryPageBean);
        return pageResult;
    }

    /**
     * 编辑权限
     * @param permission
     * @return
     */
    @RequestMapping("/update")
    public Result update(@RequestBody Permission permission) {
        try {
            permissionService.update(permission);
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.EDIT_PERMISSION_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_PERMISSION_SUCCESS);
    }

    /**
     * 删除权限
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            permissionService.delete(id);
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.DELETE_PERMISSION_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_PERMISSION_SUCCESS);
    }

    /**
     * 添加权限
     * @param permission
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Permission permission) {
        try {
            String status = permissionService.add(permission);
            if ("DuplicateKeyException".equals(status)) {
                return new Result(false, "权限名称或权限关键字已存在");
            }
        } catch (Exception e) {
            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.ADD_PERMISSION_FAIL);
        }
        return new Result(true, MessageConstant.ADD_PERMISSION_SUCCESS);
    }
}
